﻿namespace PomodoroTool
{
    #region

    using System;
    using System.Collections.Generic;
    using System.IO.IsolatedStorage;
    using System.Windows;

    using Core;

    #endregion

    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        #region Constants and Fields

        private readonly PomodoroController _controller = new PomodoroController();

        private TaskpadPresenter _taskpadPresenter;

        private TimerPresenter _timerPresenter;

        #endregion

        #region Methods

        private void _taskpadPresenter_TaskpadClosing()
        {
            _taskpadPresenter.TaskpadClosing -= _taskpadPresenter_TaskpadClosing;
            _taskpadPresenter = null;

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                _controller.StoreTasksTo(store);
            }
        }

        private void _timerPresenter_ShowTasks()
        {
            if (_taskpadPresenter == null)
            {
                var window = new TaskpadWindow();
                _taskpadPresenter = new TaskpadPresenter(window, _controller);
                window.Presenter = this._taskpadPresenter;
                _taskpadPresenter.Init();
                _taskpadPresenter.TaskpadClosing += new Action(_taskpadPresenter_TaskpadClosing);

                window.ShowDialog();
            }
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                _controller.LoadTasks(store);
            }

            var timerWindow = new TimerWindow();

            _timerPresenter = new TimerPresenter(timerWindow, _controller);
            _timerPresenter.ShowTasks += new Action(_timerPresenter_ShowTasks);
            timerWindow.Presenter = _timerPresenter;
            _timerPresenter.Init();
        }

        #endregion
    }
}